/**
 * <p>Copyright @ 2009 深圳市金绎科技发展有限公司 </p>
 * <p>All right reserved. </p>
 * <p>项目名称				： 佛山市地方公路信息资源整合</p>
 * <p>JDK使用版本号		： jdk1.6.0_12 </P>
 * <p>描述						： 自定义标签,获得单位列表</p>
 * @version						： 1.0.0
 * @author						： created by 631wj
 *
 * <p>修改历史 </p>
 *
 * <p>修改时间     						修改人员             修改内容 </p>
 * <p> 2009-03-31                    								 新建   </p>
 */
package com.pengtu.gsj.taglib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.pengtu.gsj.entity.app.User;
import com.pengtu.gsj.entity.base.LabelValue;
import com.pengtu.gsj.service.system.UserService;
import com.pengtu.gsj.utils.DateUtils;

/**
 * Tag for creating multiple &lt;select&gt; options for displaying a list of
 * country names.
 * 
 * <p>
 * <b>NOTE</b> - This tag requires a Java2 (JDK 1.2 or later) platform.
 * </p>
 * 
 * @author Jens Fischer, Matt Raible
 * @version $Revision: 1.1 $ $Date: 2006-06-10 08:00:48 -0600 (Sat, 10 Jun
 *          2006) $
 * 
 * @jsp.tag name="country" bodycontent="empty"
 */
public class LabelsTag extends TagSupport {
	/**
	 * 获得前10年到后3年的年份列表
	 */
	private static final String YEAR_LIST = "year";
	private static final String YEAR_LAST = "lastYear";
	/**
	 * serialVersionUID:TODO
	 *
	 * @since 1.0.0
	 */
	
	private static final long serialVersionUID = 1L;
	/**
	 * labels type 指定不同的集合 需定义常量
	 */
	private String type;
	/**
	 * 若定义 scope （page session request application） 将labels放入内存中 name表示 对应的Key
	 */
	private String scope;
	
	/**
	 * 表单项的name
	 */
	private String name;
	/**
	 * 默认选中项
	 */
	private String selected;

	private String prompt;
	/**
	 * 是否包含一个为空的项
	 */
	private boolean hasEmpty = true;
	/**
	 * select 表单的宽度
	 */
	private int width;
	/**
	 * 是否根据键获得对应的唯一的值
	 */
	private boolean single;

	/**
	 * 预留参数1
	 */
	private String argument1;
	/**
	 * 预留参数2
	 */
	private String argument2;
	/**
	 * 预留参数3
	 */
	private String argument3;
	/**
	 * 
	 */
	private static final String USER_NAME = "userName";
	
	@Autowired
	private UserService userService;

	@Override
	public int doStartTag() throws JspException {
		List<LabelValue> lists = new ArrayList<LabelValue>();
		if ((USER_NAME).equals(type)) {
			if (isSingle()) {
				String name = this.getNameByUsername();
				try {
					pageContext.getOut().write(name);
				} catch (IOException e) {
					throw new JspException(e);
				}
				return super.doStartTag();
			}	
		}
		else if ((YEAR_LIST).equals(type)) {
			// 获得年份的列表
			lists = this.buildYearsList();
		} 
		else if ((YEAR_LAST).equals(type)) {
			// 获得年份的列表
			lists = this.buildLastYearsList();
		} 
		if (scope != null) {
			if (scope.equals("page")) {
				pageContext.setAttribute(name, lists);
			} else if (scope.equals("request")) {
				pageContext.getRequest().setAttribute(name, lists);
			} else if (scope.equals("session")) {
				pageContext.getSession().setAttribute(name, lists);
			} else if (scope.equals("application")) {
				pageContext.getServletContext().setAttribute(name, lists);
			} else {
				throw new JspException(
						"Attribute 'scope' must be: page, request, session or application");
			}
		} else {
			StringBuilder sb = new StringBuilder();
			sb.append("<select name=\"" + name + "\" id=\"" + name
					+ "\" class=\"select\" "
					+ (width == 0 ? "" : "style=\"width: " + width + "px\"")
					+ " >\n");
			if (prompt == null && this.hasEmpty) {
				sb.append("<option value=\"\"> </option>");
			} else if (prompt != null) {
				sb.append("    <option value=\"\" >");
				sb.append(prompt);
				sb.append("</option>\n");
			}
			for (Iterator<LabelValue> i = lists.iterator(); i.hasNext();) {
				LabelValue labelValue = i.next();
				if ("optgroup".equals(labelValue.getValue())) {
					sb.append("<optgroup label=" + labelValue.getLabel() + ">");
				} else {
					sb.append("<option value=\"" + labelValue.getValue() + "\"");
					if ((selected != null)
							&& selected.equals(labelValue.getValue())) {
						sb.append(" selected=\"selected\"");
					}
					sb.append(">" + labelValue.getLabel() + "</option>\n");
				}
			}
			sb.append("</select>");

			try {
				pageContext.getOut().write(sb.toString());
			} catch (IOException io) {
				throw new JspException(io);
			}
		}

		return super.doStartTag();
	}

	private String getNameByUsername() {
		if (StringUtils.isEmpty(argument1)) {
			return "";
		} else {
			User user = userService.getUserByUsername(argument1);
			if (null == user) {
				return "";
			} else {
				return user.getName();
			}
		}
	}
	

	/**
	 * 获得年份的列表
	 * 
	 * @return
	 * 
	 *         631wj List
	 */
	protected List<LabelValue> buildYearsList() {
		List<LabelValue> units = new ArrayList<LabelValue>();
		int currentYear = DateUtils.getCurrentYear();
		for (int i = currentYear - 5; i < currentYear + 3; i++) {
			LabelValue label = new LabelValue(i+ "" , i + "");
			units.add(label);
		}
		return units;
	}
	protected List<LabelValue> buildLastYearsList() {
		List<LabelValue> units = new ArrayList<LabelValue>();
		int param =5;
		if (StringUtils.isNotEmpty(argument2)) {
			param =Integer.parseInt(argument2);
		} 
		int currentYear = DateUtils.getCurrentYear();
		for (int i = currentYear ; i >= currentYear-param; i--) {
			LabelValue label = new LabelValue(i+ "" , i + "");
			units.add(label);
		}
		return units;
	}
	/**
	 * Spring 管理bean
	 * 
	 * @param name
	 * @return
	 */
	public Object getBean(String name) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.pageContext
						.getServletContext());
		return ctx.getBean(name);
	}
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}


	public void setToScope(String scope) {
		this.scope = scope;
	}

	public String getSelected() {
		return selected;
	}

	public void setSelected(String selected) {
		this.selected = selected;
	}

	public String getPrompt() {
		return prompt;
	}

	public void setPrompt(String prompt) {
		this.prompt = prompt;
	}

	public boolean isHasEmpty() {
		return hasEmpty;
	}

	public void setHasEmpty(boolean hasEmpty) {
		this.hasEmpty = hasEmpty;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public boolean isSingle() {
		return single;
	}

	public void setSingle(boolean single) {
		this.single = single;
	}

	public String getArgument1() {
		return argument1;
	}

	public void setArgument1(String argument1) {
		this.argument1 = argument1;
	}

	public String getArgument2() {
		return argument2;
	}

	public void setArgument2(String argument2) {
		this.argument2 = argument2;
	}

	public String getArgument3() {
		return argument3;
	}

	public void setArgument3(String argument3) {
		this.argument3 = argument3;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
